package com.ruoyi.crop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.crop.api.domain.Crop;
import com.ruoyi.crop.api.domain.CropProcess;
import com.ruoyi.crop.api.domain.Sprocess;
import com.ruoyi.crop.mapper.ProcessMapper;
import com.ruoyi.crop.service.CropProcessService;
import com.ruoyi.crop.service.CropService;
import com.ruoyi.crop.service.ProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Sprocess> implements ProcessService {

    @Autowired
    private CropService cropService;
    @Autowired
    private CropProcessService cropProcessService;

    @Override
    public boolean saves(Sprocess process) {
        boolean save = this.save(process);
        ArrayList<String> list = new ArrayList<>();
        String[] cropids = process.getCropids();
        for (String cropid : cropids) {
             CropProcess cropProcess = new CropProcess();
            cropProcess.setProcessId(process.getProcessId());
            cropProcess.setCropId(cropid);
            Crop crop = cropService.getById(cropid);
            String name = crop.getName();
            list.add(name);
            cropProcessService.save(cropProcess);
        }

        String cropName = list.stream().collect(Collectors.joining(","));
        process.setCropName(cropName);
        this.updateById(process);
        return save;
    }

    @Override
    public Sprocess selectByProcessId(Integer processId) {
        return baseMapper.selectByProcessId(processId);
    }
}
